import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
// omit other imports
import { selectAllPosts, fetchPosts, postUpdated } from "./postsSlice";

export const PostsList = () => {
  // 打印action
  // console.log(
  //   postUpdated({ id: "123", title: "First Post", content: "Some text here" })
  // );
  /*
{
  type: 'posts/postUpdated',
  payload: {
    id: '123',
    title: 'First Post',
    content: 'Some text here'
  }
}
*/
  const dispatch = useDispatch();
  // const posts = useSelector(selectAllPosts);
  const posts = useSelector((state) => state.posts.posts)
  console.log(posts)
  const postStatus = useSelector((state) => state.posts.status);
   console.log(postStatus)
  useEffect(() => {
    if (postStatus === "idle") {
      dispatch(fetchPosts());
    }
  }, [postStatus, dispatch]);

  const renderedPosts = posts.map((post,idx) => (
    <article className="post-excerpt" key={idx}>
      <h3>{post.title}</h3>
      <p className="post-content">{post.content}</p>
    </article>
  ));

  return (
    <section className="posts-list">
      <h2>Posts</h2>
      {renderedPosts}
    </section>
  );
};
